<template>
  <div class="post-card" @click="$emit('click')">
    <!-- 左侧图片 -->
    <div class="post-image" v-if="post.cover_image">
      <img 
        :src="post.cover_image" 
        :alt="post.title" 
        loading="lazy"
        @error="handleImageError"
      />
      <div class="post-badge" v-if="post.is_featured">精选</div>
    </div>
    
    <!-- 中间内容区域 -->
    <div class="post-content">
      <!-- 作者和日期 -->
      <div class="post-meta">
        <span class="post-author" v-if="post.author">
          <el-avatar :src="post.author.avatar_url" :size="18">
            {{ post.author.username.charAt(0).toUpperCase() }}
          </el-avatar>
          <span class="author-name">{{ post.author.username }}</span>
        </span>
        <span class="post-author" v-else>
          <el-avatar :size="18">匿名</el-avatar>
          <span class="author-name">匿名用户</span>
        </span>
        <span class="post-date">{{ formatDate(post.published_at || post.created_at) }}</span>
      </div>
      
      <!-- 标题 -->
      <h5 class="post-title" :title="post.title">{{ post.title }}</h5>
      <!-- 调试信息 -->
      <div v-if="false" style="font-size: 10px; color: red; margin-bottom: 4px;">
        Debug: {{ JSON.stringify({title: post.title, excerpt: post.excerpt?.substring(0, 50)}) }}
      </div>
      
      <!-- 摘要 -->
      <p class="post-excerpt" v-if="post.excerpt">{{ post.excerpt }}</p>
      
      <!-- 标签 -->
      <div class="post-tags" v-if="post.tags.length > 0">
        <el-tag 
          v-for="tag in post.tags.slice(0, 3)" 
          :key="tag.id" 
          size="small"
          class="post-tag-item"
        >
          {{ tag.name }}
        </el-tag>
        <span v-if="post.tags.length > 3" class="more-tags">
          +{{ post.tags.length - 3 }}
        </span>
      </div>
      
      <!-- 统计信息和操作按钮 -->
      <div class="post-footer">
        <div class="post-stats">
          <span class="stat-item">
            <el-icon><View /></el-icon>
            <span class="stat-value">{{ post.view_count }}</span>
          </span>
          <span class="stat-item">
            <el-icon><Like /></el-icon>
            <span class="stat-value">{{ post.like_count }}</span>
          </span>
          <span class="stat-item" v-if="post.category">
            <el-icon><Folder /></el-icon>
            <span class="stat-value">{{ post.category.name }}</span>
          </span>
        </div>
        
        <!-- 操作按钮 -->
        <div class="post-actions" v-if="canEdit">
          <el-button size="small" @click.stop="editPost">
            <el-icon><Edit /></el-icon>
          </el-button>
          <el-button size="small" type="danger" @click.stop="deletePost">
            <el-icon><Delete /></el-icon>
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { usePostsStore } from '@/stores/posts'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { Post } from '@/types'

const props = defineProps<{
  post: Post
}>()

const emit = defineEmits<{
  click: []
}>()

const router = useRouter()
const userStore = useUserStore()
const postsStore = usePostsStore()

// 检查是否可以编辑/删除
const canEdit = computed(() => {
  return userStore.isLoggedIn && 
    (userStore.user?.id === props.post.author?.id || userStore.user?.is_admin)
})

const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  })
}

const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  // 如果图片加载失败，隐藏图片容器，避免无限重试
  const imageContainer = img.closest('.post-image') as HTMLElement
  if (imageContainer) {
    imageContainer.style.display = 'none'
  }
}

const editPost = () => {
  router.push(`/edit/${props.post.id}`)
}

const deletePost = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这篇文章吗？删除后无法恢复。',
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )
    
    // 调用删除API
    await postsStore.deletePost(props.post.id)
    
    ElMessage.success('文章删除成功')
    // 刷新文章列表
    window.location.reload()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除文章失败:', error)
      ElMessage.error('删除文章失败，请重试')
    }
  }
}

// 图片现在由后端自动处理，不需要前端缓存
</script>

<style scoped>
.post-card {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  border: 1px solid #f0f0f0;
  transition: all 0.3s ease;
  cursor: pointer;
  display: flex;
  height: 140px;
  margin-bottom: 16px;
}

.post-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  border-color: #e0e0e0;
}

.post-image {
  position: relative;
  width: 200px;
  height: 140px;
  flex-shrink: 0;
  overflow: hidden;
}

.image-loading {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #409eff;
  font-size: 20px;
}

.post-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.post-card:hover .post-image img {
  transform: scale(1.02);
}

.post-badge {
  position: absolute;
  top: 8px;
  right: 8px;
  background: #f56c6c;
  color: white;
  padding: 2px 6px;
  border-radius: 8px;
  font-size: 0.7rem;
  font-weight: 600;
}

.post-content {
  flex: 1;
  padding: 16px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.post-meta {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 0.8rem;
  color: #666;
}

.post-author {
  display: flex;
  align-items: center;
  gap: 6px;
}

.author-name {
  font-weight: 500;
}

.post-date {
  color: #999;
  font-size: 0.75rem;
}

.post-title {
  font-size: 0.95rem;
  font-weight: 600;
  color: #333;
  margin-bottom: 6px;
  line-height: 1.2;
  word-wrap: break-word;
  word-break: break-word;
  white-space: normal;
  display: block;
}

.post-excerpt {
  color: #666;
  line-height: 1.4;
  margin-bottom: 10px;
  font-size: 0.8rem;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.post-tags {
  display: flex;
  gap: 6px;
  margin-bottom: 12px;
  flex-wrap: wrap;
}

.post-tag-item {
  background: transparent !important;
  border: 2px solid #409eff !important;
  color: #333 !important;
  font-weight: 500;
}

/* 覆盖Element Plus的标签样式 */
.post-tags .el-tag {
  background: transparent !important;
  border: 2px solid #409eff !important;
  color: #333 !important;
  font-weight: 500;
}

.post-tags .el-tag--primary {
  background: transparent !important;
  border: 2px solid #409eff !important;
  color: #333 !important;
}

.post-tags .el-tag--light {
  background: transparent !important;
  border: 2px solid #409eff !important;
  color: #333 !important;
}

.more-tags {
  color: #999;
  font-size: 0.75rem;
}

.post-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: auto;
}

.post-stats {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 0.8rem;
  color: #999;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 2px 6px;
  background: #f8f9fa;
  border-radius: 4px;
  transition: all 0.2s ease;
}

.stat-item:hover {
  background: #e9ecef;
}

.stat-value {
  font-weight: 500;
  color: #495057;
  font-size: 0.8rem;
}

.post-actions {
  display: flex;
  gap: 6px;
}

.post-actions .el-button {
  padding: 4px 8px;
  font-size: 0.75rem;
}

@media (max-width: 768px) {
  .post-card {
    height: auto;
    flex-direction: column;
  }
  
  .post-image {
    width: 100%;
    height: 160px;
  }
  
  .post-content {
    padding: 12px;
  }
  
  .post-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
  
  .post-footer {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .post-stats {
    flex-wrap: wrap;
    gap: 8px;
  }
}
</style>
